import {WsClient} from "tsrpc-browser";
import {serviceProto, ServiceType} from "../shared/protocols/serviceProto";

export class NetManager {

    private client: WsClient<ServiceType>;

    static netManager: NetManager = new NetManager();

    isConnected() {
        return this.client.isConnected;
    }

    public static getInstance(): NetManager {
        if (!this.netManager) {
            this.netManager = new NetManager();
        }
        return this.netManager;
    }

    constructor() {
        // Use browser client or miniapp client depend on the platform 
        this.client = new WsClient(serviceProto, {
            server: `ws://localhost:3000`,
            json: true,
            // logger: console,
            heartbeat: {
                interval: 1000,
                timeout: 5000
            }
        });
        this.connect();
    }

    connect() {
        this.client.connect().then(res => {
            console.log('Connect Result:', res);
            if (res.isSucc) {
                // Connect successfully
                console.log("Connected");
            } else {
                // Connect failed
                console.log("Connect failed: " + res.errMsg);
            }
        });
    }

    sendApiMsg(username: string, callBack: (res: any) => void) {
        this.client.callApi('player/Login', {username: username, now: Date.now()}).then(callBack)
    }
}